<template>
  <view :class="[theme, `f1 oh fs-28 m-20`]" style="min-height: 900px; min-width: 1410px;">
    <view class="fd-row height-100percent">
      <view class="f1" style="min-width: 900px; ">
        <view class="f1 br-12 oh">
          <view class="fd-row bgc-hover height-120 jc-sb pl-30 pr-30" style="flex-shrink: 0;">
            <label class="color-inverse">
              {{ items[itemIndex]?.bourseName || "--" }}:{{ items[itemIndex]?.symbolName || "--" }}
            </label>
            <label class="color-grey">价格：{{ marketInfo.price || 0 }}</label>
            <label class="color-grey">
              <text>涨跌幅：</text>
              <text :class="[+marketInfo.rate > 0 ? `color-success` : `color-error`, `fw-600`]">
                {{ Number(marketInfo.rate || 0).toFixed(2) }}
              </text>
              <text class="ml-6">%</text>
            </label>
            <label class="color-grey">24H最高：{{ marketInfo.high || 0 }}</label>
            <label class="color-grey">24H最低：{{ marketInfo.low || 0 }}</label>
            <label class="color-buy">前往交易所</label>
          </view>
          <view class="f1 bgc-primary fd-row ai-center">
            <view class="ml-10">
              <label v-for="(item, index) in chartTypes" :key="index" @click="setChartType(index)"
                :class="[chartTypeIndex === index ? `bgc-hover color-inverse fw-600` : `color-grey`, `chart-types br-12 fs-26`]"
                style="padding: 30rpx 18rpx 30rpx 30rpx;">
                {{ item }}
              </label>
            </view>
            <l-echart ref="chart" enableHover />
          </view>
        </view>

        <view class="mt-20 br-12 oh" style="height: 390px;">
          <scroll-view scroll-x class="bgc-hover">
            <view class="fd-row fs-28">
              <label v-for="(option, index) in options" :key="index" @click="changeOption(index)"
                style="min-width: 120px;"
                :class="[`color-${optionIndex === index ? 'inverse' : 'grey'}`, `height-120 jc-center`]">
                {{ option }}
              </label>
            </view>
          </scroll-view>

          <view class="f1 bgc-primary oh">
            <view v-if="optionIndex === 0" class="f1 jc-center">
              <view style="padding: 30rpx 30rpx 0;">
                <view class="fd-row flex-wrap">
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 24rpx) / 3); height: 50px;">
                    项目筹码变化
                  </label>
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 24rpx) / 3); height: 50px;">
                    换筹成本
                  </label>
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 24rpx) / 3); height: 50px;">
                    当前盈亏
                  </label>
                </view>

                <view class="fd-row flex-wrap">
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 24rpx) / 3); height: 50px;">
                    0
                  </label>
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 24rpx) / 3); height: 50px;">
                    0
                  </label>
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 24rpx) / 3); height: 50px;">
                    0
                  </label>
                </view>
              </view>
              <view class="p-30">
                <view class="fd-row flex-wrap">
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 32rpx) / 4); height: 50px;" />
                  <label class="bgc-hover jc-center m-4 color-buy" style="width: calc((100% - 32rpx) / 4); height: 50px;">
                    可用
                  </label>
                  <label class="bgc-hover jc-center m-4 color-sell"
                    style="width: calc((100% - 32rpx) / 4); height: 50px;">
                    冻结
                  </label>
                  <label class="bgc-hover jc-center m-4 color-primary"
                    style="width: calc((100% - 32rpx) / 4); height: 50px;">
                    总量
                  </label>
                </view>
                <view class="fd-row flex-wrap">
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 32rpx) / 4); height: 50px;">
                    资金
                  </label>
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 32rpx) / 4); height: 50px;">
                    {{ mainAccount.tokenAmount || 0 }}
                  </label>
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 32rpx) / 4); height: 50px;">
                    {{ mainAccount.frozenTokenAmount || 0 }}
                  </label>
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 32rpx) / 4); height: 50px;">
                    {{ mainAccount.amountTotal || 0 }}
                  </label>
                </view>
                <view class="fd-row flex-wrap">
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 32rpx) / 4); height: 50px;">
                    筹码
                  </label>
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 32rpx) / 4); height: 50px;">
                    {{ mainAccount.quoteAmount || 0 }}
                  </label>
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 32rpx) / 4); height: 50px;">
                    {{ mainAccount.frozenQuoteAmount || 0 }}
                  </label>
                  <label class="bgc-hover jc-center m-4" style="width: calc((100% - 32rpx) / 4); height: 50px;">
                    {{ mainAccount.counterTotal || 0 }}
                  </label>
                </view>
              </view>
            </view>

            <view v-if="optionIndex === 1" class="f1 oh">
              <view class="fd-row jc-sa ai-center p-30 fs-24">
                <label style="width: 180px;">
                  <text>总成交量：</text>
                  <uni-easyinput v-model="batchMarchedOrderData.volume" type="number" :styles="{ color: `#fff` }" />
                </label>
                <label style="width: 180px;">
                  <text>总时长(秒)：</text>
                  <uni-easyinput v-model="batchMarchedOrderData.duration" type="number" :styles="{ color: `#fff` }" />
                </label>
                <label style="width: 180px;">
                  <text>订单数：</text>
                  <uni-easyinput v-model="batchMarchedOrderData.orderNums" type="number" :styles="{ color: `#fff` }" />
                </label>
                <button @click="batchMarchedOrder" hover-class="tap-hover"
                  class="m-0 pl-60 pr-60 bgc-btn fs-28 color-inverse">确定</button>
              </view>

              <uni-table class="f1" :loading="false" stripe emptyText="暂无更多数据">
                <uni-tr style="position: sticky; top: 0;" class="bgc-hover">
                  <uni-th align="center">时间</uni-th>
                  <uni-th align="center">价格</uni-th>
                  <uni-th align="center">数量</uni-th>
                  <uni-th align="center">总计</uni-th>
                </uni-tr>
                <uni-tr v-for="n in []" :key="n">
                  <uni-td align="center">2020-10-20</uni-td>
                  <uni-td align="center">5.235e-9</uni-td>
                  <uni-td align="center">352685625</uni-td>
                  <uni-td align="center">352685625</uni-td>
                </uni-tr>
              </uni-table>
              <uni-pagination class="m-10" show-icon total="0" :current="1" />
            </view>

            <view v-if="optionIndex === 2" class="f1 oh">
              <view class="fd-row jc-sa ai-center p-30 fs-24">
                <label style="width: 180px;">
                  <text>总成交量：</text>
                  <uni-easyinput type="number" :styles="{ color: `#fff` }" />
                </label>
                <label style="width: 180px;">
                  <text>总时长(秒)：</text>
                  <uni-easyinput type="number" :styles="{ color: `#fff` }" />
                </label>
                <view class="fd-row ai-center" style="width: 270px;">
                  <text>价格范围：</text>
                  <uni-easyinput type="number" :styles="{ color: `#fff` }" placeholder="最小价格" />
                  <text class="m-6">—</text>
                  <uni-easyinput type="number" :styles="{ color: `#fff` }" placeholder="最大价格" />
                </view>

                <view class="fd-row">
                  <button hover-class="tap-hover" class="ml-0 pl-60 pr-60 bgc-sell fs-28 color-inverse">出货</button>
                  <button hover-class="tap-hover" class="ml-20 pl-60 pr-60 bgc-buy fs-28 color-inverse">接货</button>
                </view>
              </view>

              <uni-table class="f1" :loading="false" stripe emptyText="暂无更多数据">
                <uni-tr style="position: sticky; top: 0;" class="bgc-hover">
                  <uni-th align="center">时间</uni-th>
                  <uni-th align="center">价格</uni-th>
                  <uni-th align="center">数量</uni-th>
                  <uni-th align="center">总计</uni-th>
                </uni-tr>
                <uni-tr v-for="n in 0" :key="n">
                  <uni-td align="center">2020-10-20</uni-td>
                  <uni-td align="center">5.235e-9</uni-td>
                  <uni-td align="center">352685625</uni-td>
                  <uni-td align="center">352685625</uni-td>
                </uni-tr>
              </uni-table>
              <uni-pagination class="m-10" show-icon total="0" :current="1" />
            </view>

            <view v-if="optionIndex === 3" class="f1 oh m-30 jc-center">
              <label style="width: 280px;" class="m-30">
                <text class="text-right mr-20" style="width: 100px;">挂单总成交量</text>
                <uni-easyinput v-model="batchPendingOrderData.volume" type="number" :styles="{ color: `#fff` }" />
              </label>
              <view style="width: 500px;" class="fd-row ai-center m-30">
                <text class="text-right mr-20" style="width: 100px;">单笔成交量</text>
                <uni-easyinput v-model="batchPendingOrderData.minVolume" type="number" :styles="{ color: `#fff` }"
                  placeholder="最小成交量" />
                <text class="m-6">—</text>
                <uni-easyinput v-model="batchPendingOrderData.maxVolume" type="number" :styles="{ color: `#fff` }"
                  placeholder="最大成交量" />
              </view>
              <view style="width: 500px;" class="fd-row ai-center m-30">
                <text class="text-right mr-20" style="width: 100px;">价格范围</text>
                <uni-easyinput v-model="batchPendingOrderData.minPrice" type="number" :styles="{ color: `#fff` }"
                  placeholder="最小价格" />
                <text class="m-6">—</text>
                <uni-easyinput v-model="batchPendingOrderData.maxPrice" type="number" :styles="{ color: `#fff` }"
                  placeholder="最大价格" />
              </view>

              <view class="fd-row m-30 ai-center">
                <text class="text-right mr-20" style="width: 100px;">批量操作</text>
                <button @click="batchPendingOrder(2)" hover-class="tap-hover"
                  class="m-0 pl-120 pr-120 bgc-sell fs-30 color-inverse">挂买单</button>
                <button @click="batchPendingOrder(1)" hover-class="tap-hover"
                  class="ml-30 pl-120 pr-120 bgc-buy fs-30 color-inverse">挂卖单</button>
              </view>
            </view>

            <view v-if="optionIndex === 4" class="f1 oh m-30 jc-center">
              <label style="width: 500px;" class="m-30">
                <text class="text-right mr-20" style="width: 100px;">价格范围</text>
                <uni-easyinput v-model="batchCancelOrderForm.minPrice" type="number" :styles="{ color: `#fff` }"
                  placeholder="最小价格" />
                <text class="m-6">—</text>
                <uni-easyinput v-model="batchCancelOrderForm.maxPrice" type="number" :styles="{ color: `#fff` }"
                  placeholder="最大价格" />
              </label>

              <view class="fd-row m-30 ai-center">
                <text class="text-right mr-20" style="width: 100px;">批量操作</text>
                <button @click="batchCancelOrder(1)" hover-class="tap-hover"
                  class="m-0 pl-120 pr-120 bgc-sell fs-30 color-inverse">
                  撤买单
                </button>
                <button @click="batchCancelOrder(0)" hover-class="tap-hover"
                  class="ml-30 pl-120 pr-120 bgc-buy fs-30 color-inverse">
                  撤卖单
                </button>
              </view>
            </view>

            <view v-if="optionIndex === 5" class="f1 oh">
              <uni-table class="f1 mt-10" :loading="entrusts.current.loading" stripe emptyText="暂无更多数据">
                <uni-tr style="position: sticky; top: 0;" class="bgc-hover">
                  <uni-th align="center">时间</uni-th>
                  <uni-th align="center">交易对</uni-th>
                  <uni-th align="center">方向</uni-th>
                  <uni-th align="center">价格</uni-th>
                  <uni-th align="center">委托总量</uni-th>
                  <uni-th align="center">已成交</uni-th>
                  <uni-th align="center">成交金额</uni-th>
                  <uni-th align="center">成交均价</uni-th>
                  <uni-th align="center">操作</uni-th>
                </uni-tr>
                <uni-tr v-for="(item, index) in entrusts.current.list" :key="item.id">
                  <uni-td align="center">{{ formatDate({ format: "Y-M-D h:m:s", timestamp: item.createdTime }) }}</uni-td>
                  <uni-td align="center">{{ item.symbol }}</uni-td>
                  <uni-td align="center">{{ ["卖出", "买入"][item.type] }}</uni-td>
                  <uni-td align="center">{{ item.price }}</uni-td>
                  <uni-td align="center">{{ item.number }}</uni-td>
                  <uni-td align="center">{{ item.completeNumber }}</uni-td>
                  <uni-td align="center">{{ item.completeMoney }}</uni-td>
                  <uni-td align="center">{{ item.avgPrice }}</uni-td>
                  <uni-td align="center">
                    <button @click="cancelOrder(index)" type="primary" size="mini">撤销</button>
                  </uni-td>
                </uni-tr>
              </uni-table>
              <uni-pagination :total="entrusts.current.total" :pageSize="entrusts.current.size"
                v-model="entrusts.current.current" @change="getEntrusts({ current: $event.current, type: 'current' })"
                class="m-10" show-icon />
            </view>

            <view v-if="optionIndex === 6" class="f1 oh">
              <uni-table class="f1 mt-10" :loading="entrusts.before.loading" stripe emptyText="暂无更多数据">
                <uni-tr style="position: sticky; top: 0;" class="bgc-hover">
                  <uni-th align="center">时间</uni-th>
                  <uni-th align="center">交易对</uni-th>
                  <uni-th align="center">方向</uni-th>
                  <uni-th align="center">价格</uni-th>
                  <uni-th align="center">委托总量</uni-th>
                  <uni-th align="center">已成交</uni-th>
                  <uni-th align="center">成交金额</uni-th>
                  <uni-th align="center">成交均价</uni-th>
                </uni-tr>
                <uni-tr v-for="item in entrusts.before.list" :key="item.id">
                  <uni-td align="center">{{ formatDate({ format: "Y-M-D h:m:s", timestamp: item.time }) }}</uni-td>
                  <uni-td align="center">{{ item.symbol }}</uni-td>
                  <uni-td align="center">{{ ["卖出", "买入"][item.type] }}</uni-td>
                  <uni-td align="center">{{ item.price }}</uni-td>
                  <uni-td align="center">{{ item.number }}</uni-td>
                  <uni-td align="center">{{ item.completeNumber }}</uni-td>
                  <uni-td align="center">{{ item.completeMoney }}</uni-td>
                  <uni-td align="center">{{ item.avgPrice }}</uni-td>
                </uni-tr>
              </uni-table>
              <uni-pagination :total="entrusts.before.total" :pageSize="entrusts.before.size"
                v-model="entrusts.before.current" @change="getEntrusts({ current: $event.current, type: 'before' })"
                class="m-10" show-icon />
            </view>

            <view v-if="optionIndex === 7" class="f1 oh">
              <uni-table class="f1 mt-10" :loading="false" stripe emptyText="暂无更多数据">
                <uni-tr style="position: sticky; top: 0;" class="bgc-hover">
                  <uni-th align="center">开始时间</uni-th>
                  <uni-th align="center">结束时间</uni-th>
                  <uni-th align="center">内容</uni-th>
                </uni-tr>
                <uni-tr v-for="n in []" :key="n">
                  <uni-td align="center">2020-10-20</uni-td>
                  <uni-td align="center">2020-10-21</uni-td>
                  <uni-td align="center">352685625</uni-td>
                </uni-tr>
              </uni-table>
              <uni-pagination class="m-10" show-icon total="0" :current="1" />
            </view>
          </view>
        </view>
      </view>

      <view class="ml-20">
        <view class="f1 fd-row oh" style="min-width: 500px;">
          <view class="f1 br-12 oh">
            <label class="height-120 bgc-hover pl-30 pr-30 color-inverse fs-30">买卖</label>
            <view class="f1 bgc-primary oh">
              <view class="fd-row mt-14 mb-14">
                <label :style="{ backgroundColor: tradeTypeIndex === index ? `#222a3f` : `unset` }"
                  v-for="(item, index) in tradeList" :key="index" @click="tradeTypeIndex = index"
                  class="f1 jc-center p-12 br-12">
                  <u-image width="50" height="50" :src="`/static/img/icon-${['all', 'buy', 'sell'][index]}.png`" />
                </label>
              </view>
              <view class="f1 oh text-center mb-18">
                <view class="fd-row mb-12 mr-12">
                  <text class="f1 fw-600">价格</text>
                  <text class="f1 fw-600">数量</text>
                </view>
                <scroll-view scroll-y class="f1 oh">
                  <view class="height-100percent jc-sa">
                    <view v-for="item in tradeList[tradeTypeIndex]" class="fd-row fs-24 lh-40">
                      <block v-if="item.type === 'buy'">
                        <text class="f1 color-buy">{{ item.price }}</text>
                        <text class="f1">{{ item.number }}</text>
                      </block>
                      <label v-if="item.type === 'last_price'" class="f1"
                        style="border-top: 1rpx solid #fff; border-bottom: 1rpx solid #fff; margin: 12rpx 0;">
                        <text class="f1">最新价格：{{ item.price }}</text>
                      </label>
                      <block v-if="item.type === 'sell'">
                        <text class="f1 color-sell">{{ item.price }}</text>
                        <text class="f1">{{ item.number }}</text>
                      </block>
                    </view>
                  </view>
                </scroll-view>
              </view>
            </view>
          </view>
          <view class="f1 br-12 oh ml-20">
            <label class="height-120 bgc-hover pl-30 pr-30 color-inverse fs-30">实时</label>
            <view class="f1 oh bgc-primary">
              <view class="f1 oh text-center mb-18">
                <view class="fd-row m-12">
                  <text class="f1 fw-600">价格</text>
                  <text class="f1 fw-600">数量</text>
                  <text class="f1 fw-600">时间</text>
                </view>
                <scroll-view scroll-y class="f1 oh">
                  <view class="height-100percent jc-sa">
                    <view v-for="item in liveTradeList" class="fd-row fs-24 lh-40">
                      <text :class="`f1 color-${item.type}`">{{ item.price }}</text>
                      <text class="f1">{{ item.number }}</text>
                      <text class="f1">{{ item.time }}</text>
                    </view>
                  </view>
                </scroll-view>
              </view>
            </view>
          </view>
        </view>

        <view class="br-12 oh mt-20" style="height: 390px;">
          <label class="height-120 bgc-hover pl-30 pr-30 color-inverse fs-30">手动交易</label>
          <view class="f1 fd-row bgc-primary fs-24">
            <view class="f1 p-30 jc-sb oh">
              <label class="color-grey mt-30">可用：{{ mainAccount.tokenAmount }}</label>
              <label class="mt-30">
                <text class="mr-12">价格：</text>
                <uni-easyinput type="number" v-model="transactionForm.buy.price" style="width: 0;"
                  :styles="{ color: `#ccc` }" />
              </label>
              <label class="mt-30">
                <text class="mr-12">数量：</text>
                <uni-easyinput type="number" v-model="transactionForm.buy.number" style="width: 0;"
                  :styles="{ color: `#fff` }" />
              </label>
              <slider show-value block-size="16" value="0" step="5" activeColor="#0892f5" backgroundColor="#fff" />
              <text class="color-grey mt-30">
                委托总额：{{ math.multiply(+transactionForm.buy.price, +transactionForm.buy.number).toFixed(6) }}
              </text>
              <button @click="transaction('buy')" hover-class="tap-hover"
                class="bgc-buy color-inverse fs-28 lh-88 m-30">买入</button>
            </view>
            <view class="f1 p-30 jc-sb oh">
              <label class="color-grey mt-30">可用：{{ mainAccount.quoteAmount }}</label>
              <label class="mt-30">
                <text class="mr-12">价格：</text>
                <uni-easyinput type="number" v-model="transactionForm.sell.price" style="width: 0;"
                  :styles="{ color: `#fff` }" />
              </label>
              <label class="mt-30">
                <text class="mr-12">数量：</text>
                <uni-easyinput type="number" v-model="transactionForm.sell.number" style="width: 0;"
                  :styles="{ color: `#fff` }" />
              </label>
              <slider show-value block-size="16" value="0" step="5" activeColor="#0892f5" backgroundColor="#fff" />
              <text class="color-grey mt-30">
                委托总额：{{ math.multiply(+transactionForm.sell.price, +transactionForm.sell.number).toFixed(6) }}
              </text>
              <button @click="transaction('sell')" hover-class="tap-hover"
                class="bgc-sell color-inverse fs-28 lh-88 m-30">卖出</button>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { useMapState, math } from "@/common/libs/store";
import { ref, reactive, onMounted, computed } from "vue";
import { useStore } from "vuex";
import * as echarts from 'echarts';
import { Response } from "@/common/type"
import { formatDate } from "@/common/libs/utils";
import { onLoad, onUnload } from "@dcloudio/uni-app";

const { theme, items, itemIndex } = useMapState(["theme", "items", "itemIndex"]);
const options = ["账号信息", "批量对敲", "接货出货", "批量挂单", "批量撤单", "当前委托", "历史委托", "项目规划"];
const optionIndex = ref(-1);
const tradeList = reactive<any[]>([[], [], []]);

const tradeTypeIndex = ref(0);
const chart = ref<any>(null);

const chartTypes = ["1min", "5min", "15min", "30min", "1hour", "6hour", "1day", "7day", "30day"];
const chartTypeIndex = ref(0);

const marketInfo = ref<any>({});
const mainAccount = reactive<any>({});

const transactionForm = reactive({
  buy: {
    price: "",
    number: "",
    type: 1
  },
  sell: {
    price: "",
    number: "",
    type: 0
  }
});

const batchCancelOrderForm = reactive({
  minPrice: "",
  maxPrice: "",
});

const entrusts = reactive({
  current: {
    list: [] as any[],
    total: 0,
    size: 10,
    current: 0,
    loading: false,
    key: "ordering"
  },
  before: {
    list: [] as any[],
    total: 0,
    size: 10,
    current: 0,
    loading: false,
    key: "orderHistory"
  }
});

const store = useStore();
onLoad(() => {
  changeOption(0)
  getMarketData();
  store.dispatch("getLiveTrade");
});

onUnload(() => {
  store.state.getMarketTask && clearInterval(store.state.getMarketTask);
  store.state.liveTask && clearInterval(store.state.liveTask);
});

const changeOption = (index: number) => {
  if (optionIndex.value === index) return;
  switch (index) {
    case 0:
      getMainAccount();
      break;
    case 5:
      getEntrusts({ current: 1, type: "current" });
      break;
    case 6:
      getEntrusts({ current: 1, type: "before" });
    default:
      break;
  }
  optionIndex.value = index;
}

const getMainAccount = () => {
  const { id: projectId } = items.value[itemIndex.value];
  uni.request({
    url: "/project/aminAccounts",
    data: { projectId },
    success({ data }: any) {
      Object.assign(mainAccount, data, {
        amountTotal: math.add(data.tokenAmount || 0, data.frozenTokenAmount || 0),
        counterTotal: math.add(data.quoteAmount || 0, data.frozenQuoteAmount || 0),
      });
    }
  });
}

const batchMarchedOrderData = reactive({
  volume: "",
  duration: "",
  orderNums: "",
});
const batchMarchedOrder = () => {
  const { id: projectId } = items.value[itemIndex.value];
  uni.request({
    url: "/exchange/batchMarchedOrder",
    method: "POST",
    data: {
      projectId,
      ...batchMarchedOrderData
    },
    success() {
      uni.showToast({ title: "操作成功" });
    }
  });
}

const batchPendingOrderData = reactive({
  volume: "",
  minPrice: "",
  minVolume: "",
  maxVolume: "",
  maxPrice: "",
});
const batchPendingOrder = (tradeType: 1 | 2) => {
  const { id: projectId } = items.value[itemIndex.value];
  uni.request({
    url: "/exchange/pendingOrder",
    method: "POST",
    data: {
      projectId,
      tradeType,
      ...batchPendingOrderData
    },
    success() {
      uni.showToast({ title: "操作成功" });
    }
  });
}

const batchCancelOrder = (tradeType: 0 | 1) => {
  if (!Object.values(batchCancelOrderForm).every(Boolean)) {
    uni.showToast({ title: "请输入价格范围", icon: "error" });
    return;
  }
  const { id: projectId } = items.value[itemIndex.value];
  uni.request({
    url: "/exchange/batchCancelOrder",
    method: "POST",
    data: { projectId, tradeType, ...batchCancelOrderForm },
    success() {
      uni.showToast({ title: "操作成功" });
    }
  });
}
const cancelOrder = (index: number) => {
  const { orderNo } = entrusts.current.list[index];
  uni.request({
    url: "/exchange/cancelOrder",
    method: "POST",
    data: { orderNo },
    success() {
      getEntrusts({ type: "current" });
      uni.showToast({ title: "操作成功" });
    }
  });
}
const getEntrusts = ({ current, type }: { current?: number; type: keyof typeof entrusts }) => {
  current = current || entrusts[type].current;
  entrusts[type].loading = true;
  const { id: projectId } = items.value[itemIndex.value];
  uni.request({
    url: `/exchange/${entrusts[type].key}`,
    data: { projectId, pageIndex: current, pageSize: entrusts.current.size },
    method: "POST",
    success({ data }: any) {
      entrusts[type].list = data.records;
      entrusts[type].total = data.total;
      entrusts[type].current = current!;
      entrusts[type].loading = false;
    }
  });
}

const getMarketData = () => {
  store.state.getMarketTask && clearInterval(store.state.getMarketTask);
  const { id: projectId } = items.value[itemIndex.value];
  const requestData = () => {
    uni.request({
      url: "/exchange/ticker",
      method: "POST",
      data: { projectId, type: chartTypes[chartTypeIndex.value] },
      success({ data }) {
        marketInfo.value = data;
      }
    });
    uni.request({
      url: "/exchange/depth",
      data: { projectId: items.value[itemIndex.value].id },
      method: "POST",
      success({ data }: any) {
        tradeList[0] = [
          ...data.asks.slice(0, 8).reverse().map((item: any) =>
            ({ type: "sell", price: item[0], number: item[1] })),
          {
            type: "last_price",
            price: data.last,
          },
          ...data.bids.slice(0, 8).map((item: any) =>
            ({ type: "buy", price: item[0], number: item[1] })),
        ];

        tradeList[1] = [
          ...data.bids.slice(0, 18).map((item: any) =>
            ({ type: "buy", price: item[0], number: item[1] })),
        ];

        tradeList[2] = [
          ...data.asks.slice(0, 18).map((item: any) =>
            ({ type: "sell", price: item[0], number: item[1] })),
        ]
      }
    });
    return requestData;
  }

  store.commit("setState", { key: "getMarketTask", value: setInterval(requestData(), 1000) });
}

const liveTradeList = computed(() =>
  store.state.liveTradeData.slice(0, 20).map((item: any) => ({
    type: { ask: "sell", bid: "buy" }[item.type as string],
    price: item.price,
    number: item.vol,
    time: formatDate({ format: "h:m:s", timestamp: item.tradeTime })
  }))
);

onMounted(async () => {
  setEChartsOptions();
});

const transaction = (type: keyof typeof transactionForm) => {
  if (!Object.values(transactionForm[type]).every((item) => item || item === 0)) {
    uni.showToast({ icon: "error", title: "请输入价格和数量" });
    return;
  }
  uni.request({
    url: "/exchange/order",
    method: "POST",
    data: {
      projectId: items.value[itemIndex.value].id,
      ...transactionForm[type],
    },
    success() {
      uni.showToast({ title: "操作成功" });
    }
  })
}

const setChartType = (index: number) => {
  if (chartTypeIndex.value === index) return;
  chartTypeIndex.value = index;
  setEChartsOptions();
}

function splitData(rawData: any[]) {
  // 数据意义：开盘(open)，收盘(close)，最低(lowest)，最高(highest), 交易量(volume)
  let categoryData = [];
  let values = [];
  let volumes = [];
  for (let i = 0; i < rawData.length; i++) {
    categoryData.push(rawData[i].splice(0, 1)[0]);
    values.push(rawData[i]);
    volumes.push([i, rawData[i][4], rawData[i][0] > rawData[i][1] ? 1 : -1]);
  }
  return { categoryData, values, volumes };
}
function calculateMA(dayCount: number, data: any) {
  let result = [];
  for (let i = 0, len = data.values.length; i < len; i++) {
    if (i < dayCount) {
      result.push('-');
      continue;
    }
    let sum = 0;
    for (let j = 0; j < dayCount; j++) {
      sum += data.values[i - j][1];
    }
    result.push(+(sum / dayCount));
  }

  return result;
}

const setEChartsOptions = () => {
  function setEChart(eChart: any, first = true) {
    const { id: projectId } = items.value[itemIndex.value];
    uni.request({
      url: "/exchange/kline",
      data: { projectId, type: chartTypes[chartTypeIndex.value] },
      method: "POST",
      success: <any>(({ data }: Response) => {
        const rawData = data.map((item: any) => [
          formatDate({ format: "M/D h:m", timestamp: item.klineTime }),
          item.startPrice,
          item.endPrice,
          item.lowPrice,
          item.highPrice,
          item.coinVol,
        ]);
        eChart.setOption(getEChartsOptions(splitData(rawData)));
        first && eChart.hideLoading();
      })
    });

    return setEChart;
  }

  chart.value.init(echarts, (eChart: any) => {
    eChart.showLoading({
      text: 'loading',
      color: '#41b37d',
      textColor: '#41b37d',
      maskColor: 'rgba(0, 0, 0, 0.6)',
      zlevel: 0
    });
    setEChart(eChart);
    setTimeout(setEChart(eChart), 1000);
  }, "dark");
}

const getEChartsOptions = (data: any) => {

  const upColor = '#00da3c',
    upBorderColor = '#8a0000',
    downColor = '#ec0000',
    downBorderColor = '#008f28';

  return {
    animation: true,
    backgroundColor: "transparent",
    legend: {
      top: 15,
      left: 'center',
      data: ['MA5', 'MA10', 'MA20', 'MA30'],
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      borderWidth: 1,
      borderColor: '#f8f8f8',
      padding: 10,
      textStyle: {
        color: '#f8f8f8'
      },
      backgroundColor: '#222a3f',
      // formatter(params: any) {
      //   return params;
      // }
    },
    axisPointer: {
      link: [
        {
          xAxisIndex: 'all'
        }
      ],
      label: {
        backgroundColor: '#777'
      }
    },
    toolbox: { show: false },
    brush: {
      xAxisIndex: 'all',
      brushLink: 'all',
      outOfBrush: {
        colorAlpha: 0.1
      }
    },
    visualMap: {
      show: false,
      seriesIndex: 5,
      dimension: 2,
      pieces: [
        {
          value: 1,
          color: downColor
        },
        {
          value: -1,
          color: upColor
        }
      ]
    },
    grid: [
      {
        left: '5%',
        right: '2%',
        bottom: "24%",
      },
      {
        left: '5%',
        right: '2%',
        bottom: "6%",
        height: '18%'
      }
    ],
    xAxis: [
      {
        type: 'category',
        data: data.categoryData,
        boundaryGap: false,
        axisLine: {
          onZero: false,
        },
        splitLine: {
          show: true, lineStyle: {
            color: "#222a3f"
          }
        },
        min: 'dataMin',
        max: 'dataMax',
        axisPointer: {
          z: 100
        },
        axisLabel: { show: false },
        axisTick: { show: false },
      },
      {
        type: 'category',
        gridIndex: 1,
        data: data.categoryData,
        boundaryGap: false,
        axisLine: { onZero: false },
        axisTick: { show: true },
        splitLine: {
          show: true, lineStyle: {
            color: "#222a3f"
          }
        },
        axisLabel: { show: true },
        min: 'dataMin',
        max: 'dataMax'
      }
    ],
    yAxis: [
      {
        scale: true,
        splitArea: {
          show: false
        },
        splitLine: {
          show: true, lineStyle: {
            color: "#222a3f"
          }
        },
      },
      {
        scale: true,
        gridIndex: 1,
        splitNumber: 2,
        axisLabel: { show: false },
        axisTick: { show: false },
        splitLine: {
          show: false, lineStyle: {
            color: "#222a3f"
          }
        },
      }
    ],
    dataZoom: [
      {
        type: 'inside',
        xAxisIndex: [0, 1],
        start: 1,
        end: 100
      },
    ],
    series: [
      {
        name: `${items.value[itemIndex.value]?.bourseName || "--"}:${items.value[itemIndex.value]?.symbolName || "--"}`,
        type: "candlestick",
        data: data.values,
        itemStyle: {
          color: upColor,
          color0: downColor,
          borderColor: downBorderColor,
          borderColor0: upBorderColor
        },
      },
      {
        name: 'MA5',
        type: 'line',
        showSymbol: false,
        data: calculateMA(5, data),
        smooth: true,
        lineStyle: {
          width: 1,
          opacity: 0.5
        }
      },
      {
        name: 'MA10',
        type: 'line',
        showSymbol: false,
        data: calculateMA(10, data),
        smooth: true,
        lineStyle: {
          width: 1,
          opacity: 0.5
        }
      },
      {
        name: 'MA20',
        type: 'line',
        showSymbol: false,
        data: calculateMA(20, data),
        smooth: true,
        lineStyle: {
          width: 1,
          opacity: 0.5
        }
      },
      {
        name: 'MA30',
        type: 'line',
        showSymbol: false,
        data: calculateMA(30, data),
        smooth: true,
        lineStyle: {
          width: 1,
          opacity: 0.5
        }
      },
      {
        name: 'volume',
        type: 'bar',
        xAxisIndex: 1,
        yAxisIndex: 1,
        data: data.volumes
      }
    ]
  }
}
</script>

<style lang="scss">
// scss
page {
  height: 100%;
  overflow: auto;
}

.chart-types {
  transition: all .1s ease-in-out;
  &:hover {
    background-color: #222a3f;
  }
}

::v-deep {
  &.uni-table {
    background-color: $uni-bg-color-primary;
  }

  &.uni-table-mask {
    background-color: $uni-bg-color-mask;
  }

  &.uni-table-loading {
    height: 100px;
    line-height: 100px;
  }

  &.uni-table-td {
    color: $uni-text-color-grey;
    border-bottom: none;
  }

  &.uni-table-th {
    color: $uni-text-color-disable;
    border-color: $uni-bg-color-hover;
  }

  &.uni-table .uni-table-tr:nth-child(n+2):hover,
  &.table--stripe .uni-table-tr:nth-child(2n+3) {
    background-color: $uni-bg-color-hover;
  }

  uni-slider {
    margin: 15px 0 0;

    .uni-slider-handle-wrapper {
      height: 6px;
    }

    .uni-slider-handle {
      &:hover+.uni-slider-thumb {
        transform: translate(-10%, -10%) scale(120%);
      }
    }

    .uni-slider-thumb {
      border: 2px solid $uni-color-primary;
      transition: transform 0.1s ease-in-out;
      transform: translate(-2px, -2px);
    }

    .uni-slider-value {
      font-size: 12px;

      &::after {
        content: "%";
      }
    }
  }
}
</style>